﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ReactReduxTool.Utils
{
    class CmdReplyUtil
    {

        public static CmdReplyUtil GetInstance()
        {
            return new CmdReplyUtil();
        }

        public delegate void OnExecCommandFinishedListener();

        public delegate void OnReceiveReplyListener(StreamWriter input, string reply);

        private Process mProcess;
        
        private CmdReplyUtil()
        {
            InitCmdProcess();
        }

        private void InitCmdProcess()
        {
            mProcess = new Process();
            mProcess.StartInfo.CreateNoWindow = true;
            mProcess.StartInfo.FileName = "cmd.exe";
            mProcess.StartInfo.UseShellExecute = false;
            mProcess.StartInfo.RedirectStandardError = true;
            mProcess.StartInfo.RedirectStandardInput = true;
            mProcess.StartInfo.RedirectStandardOutput = true;
        }

        public void StartCmd()
        {
            mProcess.Start();
        }

        public void CloseCmd()
        {
            mProcess.Close();
        }

        public void RunCmdWithoutReply(string command, OnExecCommandFinishedListener listener)
        {
            mProcess.StandardInput.WriteLine(command);
            new Thread(() =>
            {
                Thread.Sleep(1000);
                listener();
            }).Start();
        }

        public void RunCmdWithReplay(string command, OnReceiveReplyListener listener)
        {
            mProcess.StandardInput.WriteLine(command);
            Task<string> task = mProcess.StandardOutput.ReadToEndAsync();
            listener(mProcess.StandardInput,
                    Encoding.UTF8.GetString(Encoding.GetEncoding("GBK").GetBytes(task.Result)));
        }

    }
}
